<template>
  <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="visible"
    lock-scroll class="wpwork-dialog wpwork-dialog_center" width="600px">
    <span slot="title" class="custom-dialog-title">
      <span class="title-line"></span>
      <span class="title-text">考勤配置</span>
    </span>
    <el-form ref="dataForm" v-loading="formLoading" :model="dataForm" :rules="dataRule"
      label-width="100px" class="menuForm">
      <wpwork-form-tip-item :label="'配置作业资源'+resourcesName+'作为考勤点使用'" prop="enabledMark"
        class="leftWhite">
        <el-switch v-model="dataForm.enabledMark" :active-value="1" :inactive-value="0" />
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="考勤方式" prop="type">
        <el-select v-model="dataForm.type" placeholder="请选择考勤方式" clearable filterable>
          <el-option v-for="(item,key) in typeList" :key="key" :label="item.fullName"
            :value="item.fullName">
          </el-option>
        </el-select>
        <div
          style="color: #3C5E58; line-height: 1.5; margin-top: 5px; background-color: #FDF3EE; padding: 5px; border-radius: 4px; display: flex; align-items: center;">
          <i class="el-icon-warning"
            style="color: #FFA500; font-size: 16px; margin-right: 8px;"></i>
          <div style="flex: 1; margin-left: 4px;">
            按终端考勤时的地理位置与作业点预设位置的距离判断考勤结果，配置前确保作业资源已配置了地理位置坐标。
          </div>
        </div>
        <span>允许按终端当前轨迹线自动考勤</span><el-switch v-model="dataForm.autoattendance"
          style="margin-left: 10px;" :active-value="1" :inactive-value="0" />
        <br>
        <span>允许的距离误差</span><el-input v-model="dataForm.distance" type="number" placeholder=""
          style="width: 100px;" /> 米
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="考勤图片">
        <el-switch v-model="dataForm.mapupload" :active-value="1" :inactive-value="0" /><span
          style="margin-left: 10px;">考勤时必须上传图片</span>
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="考勤时间" tip-label="配置当前作业点的每日考勤时间" class="blue_background">
        <!-- 已选星期 -->
        <div v-if="dataForm.time && dataForm.time.length"
          style="color: #606266; font-size: 14px; display: inline-block;">
          <span style="color: #2D73F2;font-weight: 900;">已选星期：</span><span
            style="border: 1px solid #d2e4ff;border-radius: 5px;background-color: white;padding: 5px;color: #2D73F2;font-weight: 900;">{{ selectedWeekdaysText }}</span>
          <br>
        </div>

        <!-- 考勤规则摘要 -->
        <div v-if="dataForm.time && dataForm.time.length"
          style="display: inline-block; color: #606266; font-size: 14px; white-space: pre-line;"
          v-html="cronSummary">
        </div>

        <!-- 加号按钮：始终显示，与上面内容同行 -->
        <i class="el-icon-circle-plus"
          style="font-size: 20px; color: #1890FF; cursor: pointer; margin-left: 8px; vertical-align: middle;"
          @click="openRules()" plain></i>
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="考勤终端" prop="terminal" class="blue_border">
        <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
          <div v-for="(item,key) in dataForm.terminal" :key="key"
            style="background-color: #f4f8ff;padding: 5px 10px;border-radius: 5px;margin: 5px;">
            <!-- <span class="item-name">{{key+1+'、【'+item.label+'】'}}</span> -->
            <span class="item-name">{{item.label}}</span>
            <i class="el-icon-delete" style="color: #F14141;margin-left: 3px;cursor: pointer;"
              @click="deleteSelect2(item.key)"></i>
          </div>
        </div>
        <el-button type="primary" @click="openTerminal()">选择巡检终端</el-button>
      </wpwork-form-tip-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{$t('common.cancelButton')}}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="dataFormSubmit()">
        {{$t('common.confirmButton')}}</el-button>
    </span>
    <el-dialog title="终端选择" :modal="false" :visible.sync="coordinatesVisible2"
      style="margin-left: 29%;margin-top: 11%;" class="ditudialog">
      <el-transfer v-model="selectValue2" :data="list2" :titles="['待选终端','已选终端']"
        filterable></el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="coordinatesVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="selectSubmit2">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="考勤时间规则" :modal="false" :visible.sync="locationVisible" class="ditudialog">
      <!-- 星期选择 -->
      <div style="margin-bottom: 15px;">
        <span style="margin-right: 10px;">适用星期：</span>
        <el-checkbox-group v-model="weekdays" @change="handleWeekdaysChange">
          <el-checkbox label="1">周一</el-checkbox>
          <el-checkbox label="2">周二</el-checkbox>
          <el-checkbox label="3">周三</el-checkbox>
          <el-checkbox label="4">周四</el-checkbox>
          <el-checkbox label="5">周五</el-checkbox>
          <el-checkbox label="6">周六</el-checkbox>
          <el-checkbox label="7">周日</el-checkbox>
        </el-checkbox-group>
        <div v-if="!weekdays.length" style="color: #F56C6C; font-size: 12px; margin-top: 5px;">
          至少选择一个星期
        </div>
      </div>

      <!-- 原规则表格（保持不变） -->
      <div>
        <el-button size="small" type="primary" @click="addRule" icon="el-icon-plus"
          style="margin-bottom: 10px;">
          添加规则
        </el-button>

        <el-table :data="rules" size="small" border>
          <!-- 时间、类型、要求、操作列保持不变 -->

          <el-table-column label="描述" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.type" placeholder="请输入描述(例：上班)" />
            </template>
          </el-table-column>

          <el-table-column label="时间（时:分）" width="180">
            <template slot-scope="scope">
              <el-time-picker v-model="scope.row.time" format="HH:mm" value-format="HH:mm"
                placeholder="选择时间" style="width: 100%;"></el-time-picker>
            </template>
          </el-table-column>

          <el-table-column label="打卡要求" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.requirement" placeholder="选择要求">
                <el-option label="必须在时间前打卡" value="before"></el-option>
                <el-option label="必须在时间后打卡" value="after"></el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button @click="deleteRule(scope.$index)" type="danger" size="mini"
                icon="el-icon-delete"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="locationVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRules">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import iconBox from "@/components/wpwork-iconBox";
import { create, update, info } from "@/api/system/system";
import singleImg from "@/components/Upload/SingleImg";
import clipboard from "@/utils/clipboard";
import request from "@/utils/request";

export default {
  components: { iconBox, singleImg },
  data() {
    return {
      resourcesName: "",
      rules: [], // 临时编辑的规则
      weekdays: [],
      locationVisible: false,
      coordinatesVisible3: false,
      // 存储多个时间段的数组，每个元素包含一个日期范围
      timeRanges: [
        { dates: [] } // 默认一个空时间段
      ],
      coordinatesVisible2: false,
      selectValue2: [],
      list2: [
        { key: "1", label: "终端1" },
        { key: "2", label: "终端2" },
        { key: "3", label: "终端3" }
      ],
      coordinatesVisible: false,
      typeList: [
        { id: 1, fullName: "按位置" }
      ],
      visible: false,
      dataForm: {
        id: "",
        name: "",
        type: "按位置",
        terminal: [],
        coordinates: "",
        mapshow: 0,
        remarks: "",
        locationdesc: "",
        nfc: "",
        wifi: "",
        picurl1: "",
        picurl2: "",
        picurl3: "",
        dataReview: "",
        enabledMark: "",
        mapupload: "",
        value3: "",
        autoattendance: "",
        distance: "",
        time: ""
      },
      dataRule: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        type: [{ required: true, message: "类别不能为空", trigger: "blur" }],
        coordinates: [
          {
            validator: (rule, value, callback) => {
              // 获取当前表单的 type 值
              const type = this.dataForm.type;

              // 如果 type 是 '围栏' 或 '网格'，则 coordinates 必填
              if (type == "围栏" || type == "网格") { // 推荐用 id 而不是文字
                if (!value) {
                  return callback(new Error("位置坐标不能为空"));
                }
              }
              // 否则不校验（可为空）
              callback();
            },
            trigger: 'blur' // 或 'change'
          }
        ]
      },
      formLoading: false,
      iconBoxVisible: false,
      btnLoading: false,
      selfUrl: ""
    };
  },
  computed: {
    // 将 weekday 数字转为中文
    selectedWeekdaysText() {
      console.log("🚀 ~ :252 ~ cronSummary ~ 1111:", 33333)
      const weekMap = {
        '1': '周一', '2': '周二', '3': '周三',
        '4': '周四', '5': '周五', '6': '周六', '7': '周日'
      };
      // 从第一条规则中取 weekdays
      const firstRule = this.dataForm.time?.[0];
      const wd = firstRule?.weekdays || [];
      return wd.map(w => weekMap[w]).join('、') || '';
    },

    // 规则摘要（用于显示 onDuty/offDuty 等）
    cronSummary() {
      console.log("🚀 ~ :252 ~ cronSummary ~ 1111:")
      if (!this.dataForm.time?.length) return '';
      console.log("🚀 ~ :252 ~ cronSummary ~ 1111:")
      return this.dataForm.time
        .map(r => {
          const reqLabel = r.requirement === 'after' ? '后打卡' : '前打卡';
          return `${r.type} 在${r.time} ${reqLabel}`;
        })
        .join('<br>');
    }
  },
  methods: {


    openTerminal() {
      this.coordinatesVisible2 = true;
    },
    openRules() {
      const time = this.dataForm.time || [];

      // 从第一条规则中提取 weekdays 回显
      this.weekdays = time.length > 0 ? [...time[0].weekdays] : ['1', '2', '3', '4', '5']; // 默认周一

      // 初始化 rules，每条都带 weekdays
      this.rules = time.length
        ? time.map(r => ({ ...r }))
        : [{ time: '', type: '', requirement: 'before', weekdays: [...this.weekdays] }];

      this.locationVisible = true;
    },

    handleWeekdaysChange(val) {
      // 同步到所有已存在的规则
      this.rules.forEach(r => {
        r.weekdays = [...val];
      });
    },

    addRule() {
      this.rules.push({
        time: '',
        type: '',
        requirement: 'before',
        weekdays: [...this.weekdays] // 继承当前选择
      });
    },

    deleteRule(index) {
      if (this.rules.length > 1) {
        this.rules.splice(index, 1);
      } else {
        this.$message.warning('至少保留一条规则');
      }
    },

    saveRules() {
      // 验证：至少选一个星期
      if (!this.weekdays.length) {
        this.$message.error('请至少选择一个适用星期');
        return;
      }

      // 验证每条规则完整性
      for (let r of this.rules) {
        if (!r.time || !r.requirement) {
          this.$message.error('请填写完整每条规则');
          return;
        }
      }

      // 保存：每条规则都包含 weekdays
      this.$set(this.dataForm, 'time', this.rules.map(r => ({
        time: r.time,
        type: r.type,
        requirement: r.requirement,
        weekdays: [...this.weekdays] // 所有规则用相同的 weekdays
      })));
      // this.dataForm.time = this.rules.map(r => ({
      //   time: r.time,
      //   type: r.type,
      //   requirement: r.requirement,
      //   weekdays: [...this.weekdays] // 所有规则用相同的 weekdays
      // }));
      console.log("🚀 ~ :325 ~ saveRules ~ this.dataForm.time:", this.dataForm.time)

      this.$message.success('规则已保存');
      this.locationVisible = false;
    },
    deleteSelect2(id) {
      this.selectValue2 = this.selectValue2.filter(item => item != id);
      this.dataForm.terminal = this.list2.filter(item => this.selectValue2.includes(item.key))
    },
    selectSubmit2() {
      this.dataForm.terminal = this.list2.filter(item => this.selectValue2.includes(item.key))
      this.coordinatesVisible2 = false;
    },
    clearCoordinates() {
      this.dataForm.coordinates = ""
    },
    openMap() {
    },
    openWindow() {
      this.coordinatesVisible = true;
      console.log("🚀 ~ :145 ~ openWindow ~ this.coordinatesVisible:", this.coordinatesVisible)
    },
    closeDataForm() {
      this.dataForm = {
        id: "",
        name: "",
        type: "按位置",
        terminal: [],
        coordinates: "",
        mapshow: 0,
        remarks: "",
        locationdesc: "",
        nfc: "",
        wifi: "",
        picurl1: "",
        picurl2: "",
        picurl3: "",
        dataReview: "",
        enabledMark: "",
        mapupload: "",
        value3: "",
        autoattendance: "",
        distance: "",
        time: ""
      }
    },
    init(id, resourcesId, resourcesName) {
      this.closeDataForm();
      this.selectValue2 = [];
      this.dataForm.terminal = [];
      console.log("🚀 ~ :107 ~ init ~ id:", id)
      this.dataForm.id = id || "";
      this.dataForm.resourcesId = resourcesId || "";
      this.resourcesName = resourcesName || "";
      this.selfUrl = "";
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.formLoading = true;
          request({
            url: `/api/example/WorkRsattendance/getOne`,
            method: "post",
            params: { id: this.dataForm.id }
          }).then((res) => {
            console.log("🚀 ~ :168 ~ init ~ res:", res)
            this.dataForm = res.data;
            this.dataForm.terminal = JSON.parse(this.dataForm.terminal);
            this.dataForm.time = JSON.parse(this.dataForm.time);
            this.selectValue2 = this.dataForm.terminal.map(item => item.key);

            request({
              url: `/api/permission/Users/All`,
              method: "get",
              data: {
                "pageSize": 999,
                "currentPage": 1
              }
            }).then((res) => {
              console.log("🚀 ~ :178 ~ openTerminal ~ res:", res)
              this.list2 = res.data.list.map(item => ({ key: item.id, label: item.realName }));
              console.log("🚀 ~ :185 ~ openTerminal ~ this.selectValue2:", this.selectValue2)
            })
            this.$nextTick(() => {
              this.formLoading = false;
            });
          })



        } else {

          request({
            url: `/api/permission/Users/All`,
            method: "get",
            data: {
              "pageSize": 999,
              "currentPage": 1
            }
          }).then((res) => {
            console.log("🚀 ~ :178 ~ openTerminal ~ res:", res)
            this.list2 = res.data.list.map(item => ({ key: item.id, label: item.realName }));
            console.log("🚀 ~ :185 ~ openTerminal ~ this.selectValue2:", this.selectValue2)
          })
        }
      });
    },
    openIconBox() {
      this.iconBoxVisible = true;
    },
    dataFormSubmit() {
      console.log("🚀 ~ :140 ~ dataFormSubmit ~ this.dataForm:", this.dataForm)
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.formLoading = true;
          const query = {
            ...this.dataForm,
            terminal: JSON.stringify(this.dataForm.terminal),
            time: JSON.stringify(this.dataForm.time)
          };
          if (this.dataForm.id) {
            request({
              url: `/api/example/WorkRsattendance/update`,
              method: "post",
              data: query
            }).then(res => {
              console.log("🚀 ~ :210 ~ dataFormSubmit ~ res:", res)
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refreshDataList");
                }
              });
            }).catch(() => {
              this.btnLoading = false;
            });
          } else {
            request({
              url: `/api/example/WorkRsattendance/add`,
              method: "post",
              data: query
            }).then(res => {
              console.log("🚀 ~ :210 ~ dataFormSubmit ~ res:", res)
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refreshDataList");
                }
              });
            }).catch(() => {
              this.btnLoading = false;
            });

          }
        }
      });
    },
    choiceIcon(value) {
      this.dataForm.icon = value;
    },
    getSelfUrl(enCode) {
      if (!enCode) return (this.selfUrl = "");
      this.selfUrl = `${window.location.origin}/wpwork_APP_${enCode}`;
    },
    handleCopy(text, event) {
      if (text) clipboard(text, event);
    },
  }
};
</script>
<style lang="scss" scoped>
.img-list {
  display: flex;
  >>> .singleImg-container {
    margin-right: 20px;
    :last-child {
      margin-right: 0;
    }
  }
}
.icon-link {
  color: #409eff;
  margin-left: 10px;
}
.collapse {
  ::v-deep .el-collapse-item__header {
    font-size: 1rem;
    font-weight: 600;
  }
}
.leftWhite {
  ::v-deep .el-form-item__label {
    width: auto !important;
    color: #1a66f2;
    font-weight: 900;
  }
}
.ditudialog {
  margin-left: 31%;
  margin-top: 3%;
  ::v-deep .el-dialog {
    width: 741px;
  }
}

::v-deep .el-dialog__header {
  background-color: #f8f8f8;
  border-bottom: none;
}

.custom-dialog-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0;
  padding: 0;
}

.title-line {
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #3f72e7, #84b0fc);
  margin-right: 10px;
  border-radius: 2px;
}

.title-text {
  font-weight: 900;
  margin: 0;
  padding: 0;
}
.blue_background {
  ::v-deep .el-form-item__content {
    background-color: #f4f8ff;
    border: 1px solid #d2e4ff;
    border-radius: 5px;
    padding: 10px;
  }
}
.blue_border {
  ::v-deep .el-form-item__content {
    border: 1px solid #d2e4ff;
    border-radius: 5px;
    padding: 0px 0px 5px 5px;
  }
}
</style>